﻿using SqlSugar;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Infrastructure.Query;
using IM.Easy.Core.Extensions;
using IM.Easy.Entity.System;
using IM.Easy.SystemServices.IServices;
using System.Text.RegularExpressions;
using Microsoft.Extensions.FileSystemGlobbing.Internal;
using IM.Easy.SystemServices.Dtos.Versions;

namespace IM.Easy.SystemServices.Services
{
    public class ReleaseLogService : AppServices<ReleaseLog>, IReleaseLogService
    {

        public ReleaseLogService(ISqlSugarClient db) : base(db)
        {

        }

        public ReleaseLog Create(ReleaseLog entity)
        {
            // TODO: 添加创建逻辑
            return Context.Insertable(entity).ExecuteReturnEntity();
        }

        public ReleaseLog GetById(long id)
        {
            // TODO: 添加获取逻辑
            return Context.Queryable<ReleaseLog>().InSingle(id);
        }

        public PageResponse<ReleaseLogDto> GetPageList(ReleaseLogQueryDto query)
        {
            var queryable = Context.Queryable<ReleaseLog>();
            var exp = Expressionable.Create<ReleaseLog>();
            exp = exp.AndIF(query.Status != default, s => s.Status == query.Status);
            var page = queryable
                 .Where(exp.ToExpression())
                 .OrderByDescending(log => log.Major)
                 .OrderByDescending(log => log.Minor)
                 .OrderByDescending(log => log.Patch)
                 .ToPageList<ReleaseLog, ReleaseLogDto>(query);
            return page;
        }

        public bool Update(ReleaseLog entity)
        {
            // TODO: 添加更新逻辑
            return Context.Updateable(entity).ExecuteCommandHasChange();
        }

        public bool Delete(params long[] Id)
        {
            // TODO: 添加删除逻辑
            return Context.Deleteable<ReleaseLog>(Id).ExecuteCommandHasChange();
        }

        /// <summary>
        /// 判断版本号是否可用
        /// </summary>
        /// <param name="version"></param>
        /// <returns></returns>
        public bool VersionEnable(ReleaseLog releaseLog)
        {
            if (releaseLog.Major < 0 || releaseLog.Minor < 0 || releaseLog.Patch < 0)
                return false;

            bool exists = Context.Queryable<ReleaseLog>()
                .Where(log =>
                    log.Major == releaseLog.Major &&
                    log.Minor == releaseLog.Minor &&
                    log.Patch == releaseLog.Patch
                )
                .WhereIF(releaseLog.Id != default, log => log.Id != releaseLog.Id)
                .Any();

            return !exists;
        }

        /// <summary>
        /// 获取最新版本说明
        /// </summary>
        /// <returns></returns>
        public ReleaseLog GetLatest()
        {
            var query = Context.Queryable<ReleaseLog>()
                   .Where(log => log.Status == 1);
            query = query.OrderBy(log => log.Major, OrderByType.Desc)
                 .OrderBy(log => log.Minor, OrderByType.Desc)
                 .OrderBy(log => log.Patch, OrderByType.Desc);

            query = query.OrderBy(log => !string.IsNullOrEmpty(log.Suffix), OrderByType.Asc);

            // 获取第一条记录（最新版本）
            var latest = query.First();
            return latest;
        }

        public int Compare(string v1, string v2)
        {
            string pattern = @"^(\d+)\.(\d+)\.(\d+)(.*)$";
            var match1 = Regex.Match(v1, pattern);
            var match2 = Regex.Match(v2, pattern);

            // 验证格式
            if (!match1.Success || !match2.Success)
                throw new ArgumentException("版本号格式应为 x.x.x");

            // 比较主版本、次版本、修订号
            for (int i = 1; i <= 3; i++)
            {
                int num1 = int.Parse(match1.Groups[i].Value);
                int num2 = int.Parse(match2.Groups[i].Value);
                if (num1 > num2) return 1;
                if (num1 < num2) return -1;
            }
            return 0;
        }
    }
}
